import random
from flask import Blueprint, render_template, jsonify, request, redirect, session
from flask_mail import Message
from exts import mail, redis, db
from models import User
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('user', __name__, url_prefix='/user')

@bp.route('/logout')
def logout():
    session.clear() # 清除session
    return redirect('/')
@bp.route('/login', methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        form = LoginForm(request.form)
        if form.validate():
            # 验证用户
                user = User.query.filter_by(username=form.username.data).first()
                if user: # 用户存在
                    if check_password_hash(user.password, form.password.data): # 密码正确
                        session['user_id'] = user.id # 将用户id存入session
                        return redirect('/')
                    else:
                        print('密码错误')
                else:
                    print('用户不存在')
        else:
            print(form.errors)
    return redirect('/user/login')

@bp.route('/register',methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        form = RegisterForm(request.form)
        if form.validate():
            # 保存用户信息
            user = User()
            user.email = form.email.data
            user.username = form.username.data
            user.password = generate_password_hash(form.password.data)
            db.session.add(user)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                print(e)
            return redirect('/user/login')
        else:
            print(form.errors)
            return redirect('/user/register')
# 发送邮箱验证码
@bp.route('/mail_captcha')
def mail_captcha():
    captcha = random.randint(100000, 999999).__str__()
    message = Message('平台验证码', recipients=[request.args.get("email")], body=captcha)
    print(message)
    # 异步发送邮件，提升性能
    # mail.send(message)
    # 将验证码存储到缓存中
    redis.setex(f'{request.args.get("email")}', 60, captcha)
    return jsonify({'code': 200, 'msg': '验证码发送成功', 'data': None})
